<template>
  <view>
    <u-popup :show="show" mode="center" round="32rpx" @close="show = false" :safeAreaInsetBottom="false">
      <view class="qrcode flex column align-center">
        <view class="qrcode-header flex align-center">
          <image class="icon" :src="tmiIcon || require('@/static/icon/avatar.png')"></image>

          <view>
            <view class="font36 c333 bold user-name" id="userName">{{ user.tmb_name || '暂无' }}</view>
            <view class="font28 c666 user-name" id="userPhone">{{ user.tmb_position || '暂无' }}</view>
          </view>
        </view>

        <view class="qrcode-body">
          <image class="qrcode-body-img" :src="tempFilePath"></image>
        </view>

        <view class="qrcode-foot mgt40 flex align-center font32">
          <view class="item c666" @click="show = false">取消</view>
          <view class="item cfff" @click="downloadHandler">下载</view>
        </view>
      </view>
    </u-popup>

    <!-- 分享组件 -->
    <xWxmlToCanvas
      ref="xWxmlToCanvas"
      :hide="true"
      :width="canvasWidth"
      :height="canvasHeight"
      :xStyle="canvasWxStyle"
      :xWxml="canvasWxml"
    ></xWxmlToCanvas>

    <canvas class="qrcode-box" id="qrcode" canvas-id="qrcode"></canvas>
  </view>
</template>

<script>
import xWxmlToCanvas from "x-wxml-to-canvas/x-wxml-to-canvas";
import UQRCode from "uqrcodejs"; // npm install uqrcodejs
import { getQrcodeUrlApi } from '@/api/modules/mine.js'
export default {
  mixins: [],
  components: {
    xWxmlToCanvas,
  },

  props: {
    user: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      show: false,
      qrcodeUrl: "",
      // memberInfo: {
      //   tmiNickName: '彭汉博',
      //   tmiPhone: '中国科学院院长'
      // },
      canvasHeight: uni.upx2px(664),
      canvasWidth: uni.upx2px(562),
      userNameH1: {
        width: uni.upx2px(100),
        height: uni.upx2px(40),
      },
      qrcodeHeaderH1: {
        width: uni.upx2px(100),
        height: uni.upx2px(40),
      },
      qrcodeHeaderH2: {
        width: uni.upx2px(100),
        height: uni.upx2px(34),
      },
      backgroundImage: '',
      tempFilePath: "",
      remoteUrl:''
    };
  },

  computed: {
    canvasWxStyle() {
      return {
        box: {
          flexDirection: "column",
          alignItems: "center",
          paddingBottom: uni.upx2px(40),
          height: this.canvasHeight,
          width: this.canvasWidth,
          backgroundColor: "#f9f9fa",
        },
        // boxBg: {
        //   height: this.canvasHeight,
        //   width: this.canvasWidth,
        //   position: "absolute",
        //   top: 0,
        //   left: 0,
        // },
        flex: {
          display: "flex",
        },
        alignCenter: {
          alignItems: "center",
        },
        icon: {
          width: uni.upx2px(100),
          height: uni.upx2px(100),
          borderRadius: uni.upx2px(50),
          marginRight: uni.upx2px(36),
          backgroundColor: "#f9f9fa",
        },
        font32: {
          fontSize: uni.upx2px(32),
        },

        font24: {
          fontSize: uni.upx2px(24),
        },
        bold: {
          fontWeight: "bold",
        },
        c666: {
          color: "#666666",
        },

        c333: {
          color: "#333333",
        },

        qrcodeHeader: {
          height: uni.upx2px(184),
          flexDirection: "row",
        },

        qrcodeBody: {
          width: uni.upx2px(440),
          height: uni.upx2px(440),
          backgroundColor: "#ffffff",
          padding: uni.upx2px(14),
          borderRadius: uni.upx2px(24),
        },

        qrcodeBodyImage: {
          width: uni.upx2px(412),
          height: uni.upx2px(412),
        },

        qrcodeHeaderH1: this.qrcodeHeaderH1,
        qrcodeHeaderH2: this.qrcodeHeaderH2,
      };
    },
    canvasWxml() {
      return `<view class="flex box">
          <view class="qrcode-header flex align-center">
            <image class="icon" src="${this.tmiIcon}"></image>
            <view>
              <view class="bold qrcode-header-h1"><text class="font32 c333">${this.user.tmb_name || '暂无'}</text></view>
              <view class="font24 c666 qrcode-header-h2"><text>${this.user.tmb_position || '暂无'}</text></view>
            </view>
         </view>

          <view class="qrcode-body">
            <image class="qrcode-body-image" src="${this.tmiIcon}" />
          </view>
        </view>`;
    },

    tmiIcon() {
      return this.getImgUrl(this.user.tmb_icon) || require('@/static/icon/avatar.png');
    },

    shareUrl() {
      return this.remoteUrl;
    },
  },

  watch: {
    show(v) {
      if (v) {
        // this.init();
        this.getQrcodeUrl();
      }
    },
  },

  methods: {
    init() {
      var qr = new UQRCode();
      // 设置二维码内容
      qr.data = this.shareUrl;
      // 设置二维码大小，必须与canvas设置的宽高一致
      qr.size = uni.upx2px(412); // 转成像素
      // 调用制作二维码方法
      qr.make();
      // 获取canvas上下文
      var canvasContext = uni.createCanvasContext("qrcode", this); // 如果是组件，this必须传入
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext;
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas().then((res) => {
        this.$nextTick(() => {
          uni.canvasToTempFilePath(
            {
              canvasId: "qrcode",
              width: uni.upx2px(412),
              height: uni.upx2px(412),
              success: (res) => {
                console.log(res, "----");
                this.tempFilePath = res.tempFilePath;
              },
              fail: (err) => {
                console.log(err);
              },
            },
            this
          );
        });
      });
      console.log(qr, "123");
    },

    downloadHandler() {
      // if(true) {
      //   uni.$u.toast('点击下载')
      //   return 
      // }
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      const query = uni.createSelectorQuery().in(this);
      query
        .selectAll(".user-name")
        .boundingClientRect((data) => {
          const [h1, h2] = data;
          if (h1.width && h2.width) {
            this.qrcodeHeaderH1.width = h1.width;
            this.qrcodeHeaderH1.height = h1.height;
            this.qrcodeHeaderH2.width = h2.width;
            this.qrcodeHeaderH2.height = h2.height;
          }
          this.$nextTick(() => {
            this.saveImage();
          });
        })
        .exec();
    },

    async saveImage() {
      const url = await this.getQrcodeTemp();
      this.qrcodeUrl = url;
      await this.$nextTick();
      this.$refs.xWxmlToCanvas.renderToCanvas().then(() => {
        this.$refs.xWxmlToCanvas.canvasToTempFilePath().then((res) => {
          this.$refs.xWxmlToCanvas.saveImageToPhotosAlbum(res, "文件", () => {
            uni.hideLoading();
            uni.$u.toast("保存到相册成功，可以到朋友选择图片分享啦！");
            this.show = false;
          });
        }); //下载图片
      }); //渲染至canvas
    },

    getQrcodeTemp() {
      return new Promise((resolve) => {
        uni.canvasToTempFilePath(
          {
            canvasId: "qrcode",
            width: uni.upx2px(412),
            height: uni.upx2px(412),
            success: (res) => {
              if (res.tempFilePath) resolve(res.tempFilePath);
            },
            fail: (err) => {
              console.log(err);
            },
          },
          this
        );
      });
    },

    async getQrcodeUrl() {
      uni.showLoading({
        title:'加载中...'
      })
      try {
        const res = await getQrcodeUrlApi()
        console.log(res);
        this.remoteUrl = res;
        this.init()
      } catch (error) {
        
      }
      uni.hideLoading()
    } 
  },
};
</script>

<style scoped lang="scss">
.qrcode {
  width: 562rpx;
  border-radius: 32rpx;
  background: linear-gradient(180deg, rgba(248,249,253,0.8) 36%, #FAFBFD 100%);
  // background: linear-gradient(270deg, #1F64E5 2%, #72FFD7 100%);
  padding-top: 44rpx;
  overflow: hidden;

  &-header {
    .icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-right: 36rpx;
      background-color: #f9f9fa;
    }
  }

  &-body {
    width: 440rpx;
    height: 440rpx;
    border-radius: 24rpx;
    padding: 14rpx;
    background-color: white;
    margin-top: 44rpx;

    &-img {
      width: 100%;
      height: 100%;
    }
  }

  &-foot {
    width: 100%;
    height: 96rpx;
    background-color: white;

    .item {
      flex: 1;
      height: 100%;
      line-height: 96rpx;
      text-align: center;

      &:last-child {
        background-color: #481EC1;
      }
    }
  }
}

.qrcode-box {
  width: 412rpx;
  height: 412rpx;
  position: fixed;
  top: -100vh;
  left: -100vw;
}
</style>
